/*
 * Niebla.cpp
 *
 *  Created on: Apr 25, 2013
 *      Author: Hernan
 */

#include "Niebla.h"
#include <iostream>
using namespace std;

Niebla::Niebla() {
}

SDL_Surface* Niebla::obtenerEscalaGrises(SDL_Surface* imagenNormal){
	SDL_Surface* imagenDestino = SDL_CreateRGBSurface(0, imagenNormal->w, imagenNormal->h, 32, 255, 255, 255, 0);
	for (int i=0 ; i< imagenNormal->w ; i++){
		for (int j=0 ; j< imagenNormal->h ; j++){
			Uint8 r,g,b;
			//a;
			Uint32 pixel = ReadPixel(imagenNormal,i,j);
			SDL_GetRGB(pixel, imagenNormal->format, &r, &g, &b);
			r = g = b = (r+g+b)/3;
			pixel = SDL_MapRGB(imagenDestino->format, r, g, b);
			putpixel(imagenDestino,i,j,pixel);
		}
	}
	Uint32 key = this->ReadPixel( imagenDestino, 0, imagenDestino->h - 1 );
	SDL_SetColorKey( imagenDestino, SDL_SRCCOLORKEY, key );

	return imagenDestino;
}


Uint32 Niebla::ReadPixel(SDL_Surface *surface, int x, int y) {
	int bpp = surface->format->BytesPerPixel;
	/* Here p is the address to the pixel we want to retrieve */
	Uint8 *p = (Uint8 *) surface->pixels + y * surface->pitch + x * bpp;

	switch (bpp) {
	case 1:
		return *p;
		break;

	case 2:
		return *(Uint16 *) p;
		break;

	case 3:
		if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
			return p[0] << 16 | p[1] << 8 | p[2];
		else
			return p[0] | p[1] << 8 | p[2] << 16;
		break;

	case 4:
		return *(Uint32 *) p;
		break;

	default:
		return 0; /* shouldn't happen, but avoids warnings */
	}
}


void Niebla::putpixel(SDL_Surface *surface, int x, int y, Uint32 pixel){
    int bpp = surface->format->BytesPerPixel;
    /* Here p is the address to the pixel we want to set */
    Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;

    switch (bpp) {
    case 1:
    	*p = pixel;
    	break;

    case 2:
    	*(Uint16 *)p = pixel;
    	break;

    case 3:
    	if (SDL_BYTEORDER == SDL_BIG_ENDIAN) {
    		p[0] = (pixel >> 16) & 0xff;
    		p[1] = (pixel >> 8) & 0xff;
    		p[2] = pixel & 0xff;
    	}
    	else {
    		p[0] = pixel & 0xff;
    		p[1] = (pixel >> 8) & 0xff;
    		p[2] = (pixel >> 16) & 0xff;
    	}
    	break;

		case 4:
			*(Uint32 *)p = pixel;
			break;

	default:
		break;           /* shouldn't happen, but avoids warnings */
	} // switch
}


Niebla::~Niebla() {
	// TODO Auto-generated destructor stub
}

